#!/bin/bash

# 默认设置，可以通过参数覆盖
PORT=1080
USERNAME="default_user"
PASSWORD="default_password"

# 解析命令行参数
while getopts p:u:w: flag
do
    case "${flag}" in
        p) PORT=${OPTARG};;
        u) USERNAME=${OPTARG};;
        w) PASSWORD=${OPTARG};;
    esac
done

# 更新系统并安装必要的依赖
sudo apt-get update
sudo apt-get install -y python3 python3-pip

# 安装PySocks库
pip3 install PySocks

# 创建Python脚本文件
cat <<EOF > /usr/local/bin/socks5_server.py
import socket
import threading
import socks

def handle_client(client_socket, username, password):
    try:
        client_socket.recv(262)  # 收取客户端的Socks5握手包
        client_socket.send(b"\x05\x02")  # 返回要求账号密码认证

        auth_data = client_socket.recv(513)
        if auth_data[0:1] != b"\x01":
            client_socket.close()
            return

        received_username_len = auth_data[1]
        received_username = auth_data[2:2 + received_username_len].decode()
        received_password_len = auth_data[2 + received_username_len]
        received_password = auth_data[3 + received_username_len:3 + received_username_len + received_password_len].decode()

        if received_username != username or received_password != password:
            client_socket.send(b"\x01\x01")  # 返回认证失败
            client_socket.close()
            return

        client_socket.send(b"\x01\x00")  # 返回认证成功

        socks.SOCKS5Server(client_socket, None).handle_request()
    except Exception as e:
        print(f"Error handling client: {e}")
    finally:
        client_socket.close()

def start_server(port, username, password):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('0.0.0.0', port))
    server.listen(5)
    print(f"[INFO] Socks5 server is running on port {port}")

    while True:
        client_socket, addr = server.accept()
        print(f"[INFO] Accepted connection from {addr}")
        client_handler = threading.Thread(
            target=handle_client, args=(client_socket, username, password)
        )
        client_handler.start()

if __name__ == "__main__":
    PORT=$PORT
    USERNAME="$USERNAME"
    PASSWORD="$PASSWORD"

    start_server(PORT, USERNAME, PASSWORD)
EOF

# 设置执行权限
sudo chmod +x /usr/local/bin/socks5_server.py

# 创建systemd服务文件
cat <<EOF | sudo tee /etc/systemd/system/socks5.service > /dev/null
[Unit]
Description=Socks5 Proxy Server
After=network.target

[Service]
ExecStart=/usr/bin/python3 /usr/local/bin/socks5_server.py
Restart=always
User=nobody
Group=nogroup

[Install]
WantedBy=multi-user.target
EOF

# 重载systemd服务配置
sudo systemctl daemon-reload

# 启用并启动socks5服务
sudo systemctl enable socks5.service
sudo systemctl start socks5.service

echo "Socks5 server installed and started successfully on port $PORT!"